import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import Message from '@/components/utils/Message'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/HomeView.vue'),
    redirect: '/index',
    children: [
      {
        path: '/index',
        name: 'Index',
        component: () => import('@/components/index/IndexView')
      },
      {
        path: '/cate',
        name: 'Cate',
        component: () => import('@/components/category/CateView')
      },
      {
        path: '/sub',
        name: 'Sub',
        component: () => import('@/components/subcategory/SubIndex')
      },
      {
        path: '/detail',
        name: 'Detail',
        component: () => import('@/components/goodsdetail/DetailView')
      },
      {
        path: '/cart',
        name: 'cart',
        component: () => import('@/components/cart/CartView')
      },
      {
        path: '/member/checkout',
        name: 'checkout',
        component: () => import('@/components/xiadan/checkout.vue')
      },
      {
        path: '/member/payindex',
        name: 'payindex',
        component: () => import('@/components/pay/payindex.vue')
      },
      {
        path: '/member/paywancheng',
        name: 'paywancheng',
        component: () => import('@/components/pay/paywancheng.vue')
      },
      {
        path: '/member',
        name: 'member',
        component: () => import('@/components/member/MemberView.vue'),
        children: [
          {
            path: '/member/order',
            name: 'order',
            component: () => import('@/components/member/MemberOrder.vue')
          },
          {
            path: '/member/center',
            name: 'center',
            component: () => import('@/components/member/MemberCenter.vue')
          },
        ]
      },
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/LoginView')
  },
  {
    path: '/login/callback',
    name: 'login/callback',
    component: () => import('../components/login/LoginCallback')
  },
  {
    path: '/404',
    name: '404',
    component: () => import('../views/NoPage.vue')
  }
]

const router = new VueRouter({
  routes,
  //在路由切换时怎样给她切换
  scrollBehavior(to, from, savedPosition) {
    // return 期望滚动到哪个的位置
    return { x: 0, y: 0 }
  }
})
//设置全局路由导航守卫
router.beforeEach((to, from, next) => {
  // to and from are both route objects. must call `next`.
  if (to.fullPath.startsWith('/member')) {
    //要判断是否登录
    if (store.state.user && store.state.user.userinfo.token) {
      next()
    } else {
      //要跳转到登录页
      Message({ type: '请先登录', type: 'error' })
      next('/login?redirectUrl=' + to.fullPath)
    }
  } else {
    next()
  }
})


export default router
